<template>
    <div class="registration-container">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item :to="{ path: '/consulting/customer' }">我的客户</el-breadcrumb-item>
            <el-breadcrumb-item>档案信息</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="page-title">
            <h1>{{ isEditMode ? '《人工智能AI训练师》入学档案（编辑）' : '《人工智能AI训练师》入学档案（新增）' }}</h1>
        </div>

        <el-form ref="registrationFormRef" :model="registrationForm" :rules="rules" label-width="140px"
            class="registration-form" label-position="top">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="registrationForm.name" placeholder="请输入姓名" class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="registrationForm.gender">
                            <el-radio label="1">男</el-radio>
                            <el-radio label="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="入学时间" prop="enrollmentDate">
                        <el-date-picker v-model="registrationForm.enrollmentDate" type="date" placeholder="选择入学时间"
                            class="custom-input"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="身份证号码" prop="idCard">
                        <el-input v-model="registrationForm.idCard" placeholder="请输入身份证号码"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="出生日期" prop="birthDate">
                        <el-date-picker v-model="registrationForm.birthDate" type="date" placeholder="选择出生日期"
                            class="custom-input"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="registrationForm.phone" placeholder="请输入手机号" class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="微信号" prop="wechatId">
                        <el-input v-model="registrationForm.wechatId" placeholder="请输入微信号"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter='20'>
                <el-col :span="8">
                    <el-form-item label="最高学历" prop="education">
                        <el-select v-model="registrationForm.education" placeholder="请选择最高学历" class="custom-select">
                            <el-option label="高中及以下" value="highSchool"></el-option>
                            <el-option label="专科" value="juniorCollege"></el-option>
                            <el-option label="本科" value="bachelor"></el-option>
                            <el-option label="硕士" value="master"></el-option>
                            <el-option label="博士及以上" value="phd"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="专业" prop="major">
                        <el-input v-model="registrationForm.major" placeholder="请输入专业" class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="目前状态" prop="currentStatus">
                        <el-select v-model="registrationForm.currentStatus" placeholder="请选择目前状态" class="custom-select">
                            <el-option label="在读" value="在读"></el-option>
                            <el-option label="待业" value="待业"></el-option>
                            <el-option label="在职" value="在职"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="目前薪资" prop="currentSalary">
                        <el-input v-model="registrationForm.currentSalary" placeholder="请输入目前薪资"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="目标就业城市" prop="targetCity">
                        <el-input v-model="registrationForm.targetCity" placeholder="请输入目标就业城市"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="期望薪资" prop="expectedSalary">
                        <el-input v-model="registrationForm.expectedSalary" placeholder="请输入期望薪资"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="学习目标" prop="studyGoal">
                        <el-input v-model="registrationForm.studyGoal" placeholder="请输入学习目标"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="紧急联系人" prop="emergencyContact">
                        <el-input v-model="registrationForm.emergencyContact" placeholder="请输入紧急联系人"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="紧急联系人电话" prop="emergencyContactPhone">
                        <el-input v-model="registrationForm.emergencyContactPhone" placeholder="请输入紧急联系人电话"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="渠道备注" prop="channelRemark">
                        <el-input v-model="registrationForm.channelRemark" placeholder="请输入渠道备注"
                            class="custom-input"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <div class="form-actions">
                <el-button type="primary" @click="handleSubmit">
                    {{ isEditMode ? '保存修改' : '提交档案' }}
                </el-button>
                <el-button @click="handleExit">退出</el-button>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getEnrollmentRecordDetail, addEnrollmentRecord, updateEnrollmentRecord } from '../../../api/consultant/record'

const route = useRoute();
const router = useRouter();

// 1. 接收路由参数
const rowData = route.query.data ? JSON.parse(decodeURIComponent(route.query.data)) : null;
const registrationFormRef = ref(null);

// 2. 新增：显式标记当前模式
const isEditMode = ref(false);

// 3. 表单数据
const registrationForm = reactive({
    id: '',
    externalUserid: '',
    name: '',
    gender: '1',
    enrollmentDate: '',
    idCard: '',
    birthDate: '',
    phone: '',
    wechatId: '',
    education: '',
    major: '',
    currentStatus: '',
    currentSalary: '',
    targetCity: '',
    expectedSalary: '',
    studyGoal: '',
    emergencyContact: '',
    emergencyContactPhone: '',
    channelRemark: ''
});

// 4. 封装：数据赋值函数
const setFormData = (data, isFromDetail = false) => {
    registrationForm.externalUserid = rowData.externalUserid || '';
    registrationForm.name = data.name || '';
    registrationForm.gender = data.gender ? String(data.gender) : '1';
    registrationForm.phone = data.phone || '';
    registrationForm.wechatId = data.wechatId || '';
    registrationForm.channelRemark = data.channelRemark || '';

    if (isFromDetail) {
        registrationForm.id = data.id || '';
        registrationForm.enrollmentDate = data.enrollmentDate;
        registrationForm.idCard = data.idCard || '';
        registrationForm.birthDate = data.birthDate;
        registrationForm.education = data.education || '';
        registrationForm.major = data.major || '';
        registrationForm.currentStatus = data.currentStatus || '';
        registrationForm.currentSalary = data.currentSalary || '';
        registrationForm.targetCity = data.targetCity || '';
        registrationForm.expectedSalary = data.expectedSalary || '';
        registrationForm.studyGoal = data.studyGoal || '';
        registrationForm.emergencyContact = data.emergencyContact || '';
        registrationForm.emergencyContactPhone = data.emergencyContactPhone || '';
    } else {
        registrationForm.id = '';
        registrationForm.name = rowData.studentName || '';
        registrationForm.phone = rowData.mobile || '';
        registrationForm.wechatId = rowData.wechatNumber || '';
        registrationForm.channelRemark = rowData.remark || '';
    }
};

// 5. 生命周期：加载数据
onMounted(async () => {
    console.log('传递过来的rowData:', rowData);

    if (!rowData || !rowData.externalUserid) {
        ElMessage.warning('缺少用户唯一标识，无法加载数据');
        return;
    }

    try {
        const response = await getEnrollmentRecordDetail(rowData.externalUserid);

        if (response.code === 200) {
            const detailData = response.data;
            if (detailData) {
                isEditMode.value = true;
                setFormData(detailData, true);
                ElMessage.success('已加载档案信息，当前为编辑模式');
            } else {
                isEditMode.value = false;
                setFormData({}, false);
                ElMessage.info('未查询到档案，当前为新增模式');
            }
        } else {
            isEditMode.value = false;
            setFormData({}, false);
            ElMessage.error(`获取档案失败：${response.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('加载档案接口请求失败:', error);
        isEditMode.value = false;
        setFormData({}, false);
        ElMessage.error('网络异常，请检查网络后重试');
    }
});

// 6. 表单校验规则
const rules = reactive({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    idCard: [
        { required: false, message: '请输入身份证号码', trigger: 'blur' },
        { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入有效的身份证号码', trigger: 'blur' }
    ],
    phone: [
        { required: false, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
    ]
});

// 7. 提交处理
const handleSubmit = async () => {
    registrationFormRef.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('请完善表单必填信息');
            return false;
        }

        if (!registrationForm.externalUserid) {
            ElMessage.error('缺少用户信息，无法提交');
            return;
        }

        try {
            const submitData = {
                ...registrationForm,
                id: isEditMode.value ? registrationForm.id : rowData.id
            };

            const response = isEditMode.value
                ? await updateEnrollmentRecord(submitData)
                : await addEnrollmentRecord(submitData);

            if (response.code === 200) {
                const successMsg = isEditMode.value
                    ? '档案修改成功！'
                    : '档案提交成功！';
                ElMessage.success(successMsg);
                // handleExit();
            } else {
                ElMessage.error(response.message || '操作失败，请重试');
            }
        } catch (error) {
            console.error(`${isEditMode.value ? '修改' : '新增'}档案出错:", error`);
            ElMessage.error('网络异常，操作失败');
        }
    });
};

// 8. 退出逻辑
const handleExit = () => {
    router.push({ path: '/consulting/customer' });
};
</script>

<style scoped>
.registration-container {
    width: 100%;
}

.header {
    margin-bottom: 5px;
    padding: 15px 0;
    font-size: 20px;
}

.page-title {
    background: rgba(32, 127, 252, 0.04);
    border-radius: 6px;
    margin-bottom: 20px;
}

.page-title h1 {
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    padding: 8px 10px;
}

.form-card {
    overflow: hidden;
}

.custom-input,
.custom-select {
    width: 100%;
}

.form-actions {
    display: flex;
    gap: 20px;
    margin-top: 20px;
}

:deep(.el-form-item__label.is-required:not(.is-no-asterisk)::before) {
    content: '*';
    color: #ff4d4f;
    margin-right: 4px;
}
</style>